package KK.net.Proxy
{
	import KK.Data.GameData;
	import KK.Data.ProtocolData;
	import KK.Event.ModuleEvent;
	import KK.Event.RegisterUserEvent;
	import KK.GameBase.IMessageQueue;
	import KK.Global.Game;
	import KK.net.Command.CommandID;
	import KK.net.Data.Head;
	import KK.net.Event.SocketEvent;
	import KK.net.ProxyManager;
	
	import Protocol.EProtocol;
	import Protocol.SLogin;
	import Protocol.SLoginRet;
	import Protocol.SRegister;
	import Protocol.SRegisterRet;
	
	import flash.utils.ByteArray;

	public class LoginProxy extends Proxy implements IProxy
	{
		private var loginret:SLoginRet;
		public function LoginProxy()
		{
			//TODO: implement function
			init();
		}
		
		public function init():void{
			
			
			ProxyManager.RegisterProgress(CommandID.IC_LOGIN,onLogin);
			ProxyManager.RegisterCommand(EProtocol.EProtocol_LoginRet,LoginRet); 
			ProxyManager.RegisterCommand(EProtocol.EProtocol_RegisterRet,onRegisterRet); 
			loginret=new SLoginRet();
		}
		
		/**
		 * 登陆 
		 * 
		 */
		private function onLogin():void{
//			onRegister(new RegisterUserEvent("","aece",1,1));
			var result:SLogin=new SLogin();
			result.userName=Game.OpenID;
			
			Send(EProtocol.EProtocol_Login,result);
		}
		
		
		/**
		 * 绑定事件 
		 * @param _event
		 * @return 
		 * 
		 */
		override public function BindEvent(_event:IMessageQueue):Boolean{
			var result:Boolean=super.BindEvent(_event);
			AttentionMessage(RegisterUserEvent.REGISTER,onRegister);
			return result;
		}
		
		/**
		 * 注册 
		 * @param event
		 * 
		 */
		private function onRegister(event:RegisterUserEvent):void{ 
			var user:Object=event.User;
			
			var Info:SRegister=new SRegister();
			
			Info.name=user.name;
			Info.userName=Game.OpenID; 
			Info.picId=event.User.image;
			Info.sex=event.User.sex;
			
			Send(EProtocol.EProtocol_Register,Info);
		}
		/**
		 * 登陆服务器返回  
		 * @param head
		 * 
		 */
		private function LoginRet(data:ByteArray):void{
			
			Publish(new ModuleEvent(ModuleEvent.HIDE,GameData.M_RegisterID));
			data.position=0;
			loginret.Unserialize(data);
			Game.LogicAddress=loginret.addr;  
			LogInfo("登陆返回:",Game.LogicAddress);
			Connect(loginret.addr);
		}
		
		/**
		 * 注册 
		 * @param data
		 * 
		 */
		private function onRegisterRet(data:ByteArray):void{
			var ret:SRegisterRet=new SRegisterRet();
			
			ret.Unserialize(data);
			if(ret.result){
				//注册成功 
				Publish(new ModuleEvent(ModuleEvent.HIDE,GameData.ModuleID['REGISTER']));
			}
			LogInfo("注册返回 : ",ret.result);
		}
		 
		
		/**
		 * 连接逻辑服务器  
		 * @param addr
		 * 
		 */
		private function Connect(addr:String):void{ 
			Game.network.connect(addr);
		}
	}
}